package com.luocj.looook.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.luocj.looook.R;
import com.luocj.looook.activity.PermissionActivity;
import com.luocj.looook.adapter.BaseRecyclerAdapter;
import com.luocj.looook.adapter.SmartViewHolder;
import com.luocj.looook.base.BaseFragment;
import com.luocj.looook.event.TestEvent;
import com.luocj.looook.model.gankApi.FuLi;
import com.luocj.looook.ui.CircleView;
import com.luocj.looook.ui.progressview.CircleProgressView;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by luocj515 on 2017/11/24.
 * 项目名称：LooooK
 * 类描述：
 * 创建人：hasee
 * 创建时间：2017/11/24 20:19
 * 修改备注：
 */

public class TESTFragment extends BaseFragment {
    private String TAG = TESTFragment.class.getSimpleName();
    private CircleView circleView;
    private int sweepAngle = 0;

    private boolean togle = false;

    private List<String> mDatas = new ArrayList<>();
    private List<String> mChecks = new ArrayList<>();

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    sweepAngle++;
                    if (sweepAngle <= 270) {
                        circleView.setSweetAngle(sweepAngle);
                        Message message = mHandler.obtainMessage(1);
                        this.sendMessageDelayed(message, 500);
                    }
                    break;
                default:
                    break;
            }
            super.handleMessage(msg);
        }
    };
    private SmartRefreshLayout smartreFreshLayout;
    private RecyclerView recyclerView;
    private BaseRecyclerAdapter<String> adapter;
    private TextView tvTotal;
    private ImageView mImageView;
    private int PAGE_SIZE = 5;
    private CircleProgressView progressview;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_test;
    }

    @Override
    protected void initData() {
        for (int i = 0; i < 10; i++) {
            mDatas.add("item:  " + i);
        }
    }


    @Override
    protected void initView() {

        progressview = mContentView.findViewById(R.id.circle);
        progressview.setProgress(0);
        progressview.setTextVisible(true);
        progressview.setReachCapRound(false);
        progressview.setMax(20);

        progressview.setProgressInTime(0, 20, 20 * 1000);


        mContentView.findViewById(R.id.btn_permission).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Logger.i("request permission");

//                int camear = ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA);
//                if (camear != PackageManager.PERMISSION_GRANTED) {
//                    ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1001);
//                } else {
//                    Logger.i("321");
                getActivity().startActivity(new Intent(getActivity(), PermissionActivity.class));

//                }
            }
        });

        tvTotal = mContentView.findViewById(R.id.tv_total);
        mImageView = mContentView.findViewById(R.id.imageview);
        mImageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

//                showDialog();

//                if (shapeLoading == null) {
//                    shapeLoading = new RxDialogShapeLoading(mContentView.getContext());
//                }
//                if (dialogSure == null) {
//                    dialogSure = new RxDialogSure(mContentView.getContext());
//                    dialogSure.setTitle("haha");
//                    dialogSure.setContent("feifei");
//                    dialogSure.setSureListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            dialogSure.dismiss();
//                        }
//                    });
//
//                    dialogSure.getTitleView().setOnClickListener(new View.OnClickListener() {
//                        @Override
//                        public void onClick(View view) {
//                            Toast.makeText(mContentView.getContext(),"123",Toast.LENGTH_SHORT).show();
//                        }
//                    });
//                }
//
//                if (!togle) {
////                    shapeLoading.show();
//                    dialogSure.show();
//                } else {
//                    dialogSure.dismiss();
////                    shapeLoading.dismiss();
//                }
//
//                togle = !togle;

            }
        });

        smartreFreshLayout = mContentView.findViewById(R.id.smartrefreshlayout_test);
        recyclerView = mContentView.findViewById(R.id.recyclerview_test);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new BaseRecyclerAdapter<String>(mDatas, R.layout.item_test, new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Logger.i(position +"");
            }
        }) {
            @Override
            protected void onBindViewHolder(SmartViewHolder holder, String model, final int position) {
                TextView test = holder.itemView.findViewById(R.id.tv_test);
                test.setText(model);
                CheckBox checkBox = holder.itemView.findViewById(R.id.checkbox);
                checkBox.setChecked(false);
                checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        Log.i(TAG, "onCheckedChanged: " + b + "position:" + position);
                    }
                });
            }
        };
        recyclerView.setAdapter(adapter);

        smartreFreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refrshData(true);
                    }
                }, 2000);
            }
        });

        smartreFreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                refreshlayout.getLayout().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        refrshData(false);
                    }
                }, 2000);
            }
        });

        circleView = mContentView.findViewById(R.id.circleview);
        mContentView.findViewById(R.id.btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i(TAG, "onClick: ");
                mHandler.sendMessageDelayed(mHandler.obtainMessage(1), 500);
            }
        });

        mContentView.findViewById(R.id.btn1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                PAGE_SIZE = PAGE_SIZE + 5;
                String url = "http://gank.io/api/data/%E7%A6%8F%E5%88%A9/" + PAGE_SIZE + "/1";
                OkGo.<String>get(url)
                        .tag(TAG)
                        .execute(new StringCallback() {
                            @Override
                            public void onSuccess(Response<String> response) {
                                Log.i(TAG, "onSuccess: " + response.body().toString());
                                FuLi fuLi = JSONObject.parseObject(response.body().toString(), FuLi.class);
                                List<FuLi.ResultsBean> results = fuLi.getResults();
                                Log.i(TAG, "onSuccess: " + results.size());
                                String picUrl = results.get(0).getUrl();
                                if (picUrl != null) {
                                    tvTotal.setText(picUrl);
                                    Glide.with(getActivity())
                                            .load(picUrl)
                                            .placeholder(R.mipmap.ic_launcher)
                                            .centerCrop()
                                            .into(mImageView);
                                }
                            }

                            @Override
                            public void onError(Response<String> response) {
                                Log.i(TAG, "onError: " + response.toString());
                            }
                        });
            }
        });
    }

    @Override
    public void onItemClick(Object o, int position) {
        Log.i(TAG, "onItemClick: " + position);
    }

    private void refrshData(boolean isRefresh) {
        if (isRefresh) {
            if (mDatas.size() != 0) {
                mDatas.clear();
            }
            initData();
            adapter.refresh(mDatas);
            smartreFreshLayout.finishRefresh();
            smartreFreshLayout.setLoadmoreFinished(false);
        } else {
            adapter.loadmore(mDatas);
            smartreFreshLayout.finishLoadmore();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGetEvent(TestEvent event) {

        int position = event.getPosition();
        Toast.makeText(getActivity(), position + "--" + event.getContent(), Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        progressview.setProgress(0);
        progressview.setTextVisible(true);
        progressview.setReachCapRound(false);
        progressview.setMax(20);
        Log.i(TAG, "onResume: ");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Log.i(TAG, "onDestroy: ");
    }


}
